package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

// 一条日志，序列化到 mongodb 需要转bson
type LogRecord struct {
	JobName   string    `bson:"jobName"`   // 任务名称
	Command   string    `bson:"command"`   // 命令
	Err       string    `bson:"err"`       // 脚本错误
	Content   string    `bson:"content"`   // 脚本输出
	TimePoint TimePoint `bson:"timePoint"` // 时间
}

// 小于时间 {"$it":timestamp}
type TimeBeforeCond struct {
	Before int64 `bson:"$lt"`
}

// {"timePoint.startTime":{"$it":timestamp}}
type DeleteCond struct {
	BeforeCond TimeBeforeCond `bson:"timePoint.startTime"`
}

func main() {
	var (
		//ctx        context.Context
		client     *mongo.Client
		database   *mongo.Database
		collection *mongo.Collection
		err        error
		deleteCond *DeleteCond
		delResp *mongo.DeleteResult
	)
	//ctx, _ = context.WithTimeout(context.Background(), 5*time.Second)
	if client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://127.0.0.1:27017")); err != nil {
		fmt.Println(err)
		return
	}

	// 选择db
	database = client.Database("cron")

	// 选择表，插入记录的时候才会真正创建表
	collection = database.Collection("log")

	// delete condition
	deleteCond = &DeleteCond{
		BeforeCond:TimeBeforeCond{time.Now().Unix()},
	}

	// delete
	if delResp,err = collection.DeleteMany(context.TODO(),deleteCond); err!=nil{
		fmt.Println(err)
		return
	}

	fmt.Println("删除了",delResp.DeletedCount,"条")
}
